//
//  JobDetailViewController.m
//  XRSquare
//
//  Created by UaenaMo on 2018/8/15.
//  Copyright © 2018年 UaenaMo. All rights reserved.
//

#import "JobDetailViewController.h"
#import "JobTableViewCell.h"
#import "JobDesctiptionTableViewCell.h"
#import "ChatViewController.h"
#import "PersonDetailViewController.h"
#import "JobDescribeTableViewCell.h"
#import "BaoMingView.h"
#import "PGDatePickManager.h"
#import <UMShare/UMShare.h>

@interface JobDetailViewController ()<UITableViewDelegate,UITableViewDataSource,BaoMingViewDelegate,PGDatePickerDelegate>
{
    UITableView * contentTableView;
    NSDictionary * contentData;
    UIButton * baoming;
    UIButton * sixin;
    BaoMingView * baomingv;
    
    NSString * jobDescribe;
    UIBarButtonItem * collectItem;
}
@end

@implementation JobDetailViewController

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    jobDescribe = @"";
    
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"share-2"] style:UIBarButtonItemStylePlain target:self action:@selector(shareAction)];
    
    CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
    CGRect rectNav = self.navigationController.navigationBar.frame;

    contentTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, rectStatus.size.height + rectNav.size.height, ScreenWidth, ScreenHeight - rectStatus.size.height - rectNav.size.height - 50) style:UITableViewStylePlain];
    contentTableView.delegate = self;
    contentTableView.dataSource = self;
    contentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:contentTableView];

    [self requestData];
    
    sixin = [[UIButton alloc]initWithFrame:CGRectMake(0, ScreenHeight - 50, ScreenWidth/2, 50)];
    sixin.backgroundColor = [UIColor whiteColor];
    sixin.titleLabel.font = [UIFont systemFontOfSize:15];
    [sixin setTitle:@"私信" forState:UIControlStateNormal];
    [sixin setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [sixin addTarget:self action:@selector(sixinAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sixin];
    
    baoming = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/2, ScreenHeight - 50, ScreenWidth/2, 50)];
    [baoming setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
    [baoming setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [baoming setTitle:@"报名" forState:UIControlStateNormal];
    baoming.titleLabel.font = [UIFont systemFontOfSize:15];
    baoming.backgroundColor = themeColor;
    [baoming addTarget:self action:@selector(baomingAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:baoming];
    
    UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 50, ScreenWidth, 0.5)];
    line.backgroundColor = [UIColor colorFromHexCode:@"b3b3b3"];
    [self.view addSubview:line];
}

-(void)shareAction
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * item1 = [UIAlertAction actionWithTitle:@"QQ" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self qqAction];
    }];
    UIAlertAction * item2 = [UIAlertAction actionWithTitle:@"微信" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self wechatFriendAction];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertController addAction:item1];
    [alertController addAction:item2];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)wechatFriendAction
{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //创建网页内容对象
    NSString * description = [contentData objectForKey:@"TaskName"];
    NSString * imageUrl = [NSString stringWithFormat:@"https://pic.xrsquare.com/%@",[contentData objectForKey:@"UserHeadPic"]];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"蓄锐广场" descr:description thumImage:imageUrl];
    //设置网页地址
    if (self.demand)
    {
        shareObject.webpageUrl = [NSString stringWithFormat:@"https://m.xrsquare.com/demanddetail?taskid=%@",self.contentid];

    }
    else
    {
        shareObject.webpageUrl = [NSString stringWithFormat:@"https://m.xrsquare.com/lessondetail?taskid=%@",self.contentid];

    }
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
}

-(void)qqAction
{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //创建网页内容对象
    NSString * description = [contentData objectForKey:@"TaskName"];
    NSString * imageUrl = [NSString stringWithFormat:@"https://pic.xrsquare.com/%@",[contentData objectForKey:@"UserHeadPic"]];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"蓄锐广场" descr:description thumImage:imageUrl];
    //设置网页地址
    if (self.demand)
    {
        shareObject.webpageUrl = [NSString stringWithFormat:@"https://m.xrsquare.com/demanddetail?taskid=%@",self.contentid];
        
    }
    else
    {
        shareObject.webpageUrl = [NSString stringWithFormat:@"https://m.xrsquare.com/lessondetail?taskid=%@",self.contentid];
        
    }
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_QQ messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
}



-(void)sixinAction
{
    ChatViewController * chat = [[ChatViewController alloc]init];
    chat.contentid = [contentData objectForKey:@"groupID"];
    chat.targetName = [contentData objectForKey:@"NickName"];
    chat.targetUid = [contentData objectForKey:@"UserUID"];
    chat.targetPic = [contentData objectForKey:@"UserHeadPic"];
    [self.navigationController pushViewController:chat animated:YES];
}

-(void)baomingAction
{
    baomingv = [[BaoMingView alloc]initWithFrame:CGRectZero];
    baomingv.delegate = self;
    baomingv.contentId = [contentData objectForKey:@"TaskID"];
    baomingv.week = [contentData objectForKey:@"TaskWeekday"];
    [self.view addSubview:baomingv];
}
 
-(void)finished
{
    [self requestData];
}

-(void)startTime
{
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    datePickManager.isShadeBackgroud = true;
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.delegate = self;
    datePicker.tag = 1;
    datePicker.datePickerType = PGPickerViewType2;
    datePicker.datePickerMode = PGDatePickerModeDateHourMinute;
    [self presentViewController:datePickManager animated:false completion:nil];
    
    [datePicker setDate:[NSDate date] animated:NO];
}

-(void)endTime
{
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    datePickManager.isShadeBackgroud = true;
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.delegate = self;
    datePicker.tag = 2;
    datePicker.datePickerType = PGPickerViewType2;
    datePicker.datePickerMode = PGDatePickerModeDateHourMinute;
    [self presentViewController:datePickManager animated:false completion:nil];
    
    [datePicker setDate:[NSDate date] animated:NO];
}

#pragma PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents {
    NSLog(@"dateComponents = %@", dateComponents);
    
    NSCalendar * calendar = [NSCalendar currentCalendar];
    NSDate * date = [calendar dateFromComponents:dateComponents];
    
    if (datePicker.tag == 1)
    {
        NSString * startTime = [NSString stringWithFormat:@"%ld-%02ld-%02ld %02ld:%02ld:%02ld",(long)dateComponents.year,(long)dateComponents.month,dateComponents.day,dateComponents.hour,dateComponents.minute,dateComponents.second];
        [baomingv selectStartTime:startTime];
    }
    if (datePicker.tag == 2)
    {
        NSString * endtime = [NSString stringWithFormat:@"%ld-%02ld-%02ld %02ld:%02ld:%02ld",(long)dateComponents.year,(long)dateComponents.month,dateComponents.day,dateComponents.hour,dateComponents.minute,dateComponents.second];
        [baomingv selectEndTime:endtime];
    }
}

-(void)requestData
{
    if (self.demand)
    {
        [NetRequestCenter demanddetailwithtaskid:self.contentid result:^(BOOL success, NSDictionary *resultDic) {
            if (success)
            {
                contentData = [resultDic objectForKey:@"data"];

                if ([[NSString stringWithFormat:@"%@",[contentData objectForKey:@"EnrollStatusContent"]]isEqualToString:@"报名"])
                {
                    [baoming setTitle:@"报名" forState:UIControlStateNormal];
                    baoming.backgroundColor = themeColor;
                }
                else
                {
                    [baoming setTitle:[contentData objectForKey:@"EnrollStatusContent"] forState:UIControlStateNormal];
                    baoming.enabled = NO;
                    baoming.backgroundColor = [UIColor colorFromHexCode:@"b3b3b3"];
                }
                
                if ([[contentData objectForKey:@""]isEqualToString:@""])
                {
                    collectItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"collect"] style:UIBarButtonItemStylePlain target:self action:@selector(favAction)];
                }
                else
                {
                    collectItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"collect"] style:UIBarButtonItemStylePlain target:self action:@selector(favAction)];
                }
                
                jobDescribe = [NSString stringWithFormat:@"%@",[contentData objectForKey:@"TaskDescription"]];
                [contentTableView reloadData];
            }
            else
            {
                [SVProgressHUD showErrorWithStatus:[resultDic objectForKey:@"message"]];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }
    else
    {
        [NetRequestCenter lessondetailwithtaskid:self.contentid Result:^(BOOL success, NSDictionary *resultDic) {
            if (success)
            {
                contentData = [resultDic objectForKey:@"data"];

                if ([[NSString stringWithFormat:@"%@",[contentData objectForKey:@"EnrollStatusContent"]]isEqualToString:@"报名"])
                {
                    [baoming setTitle:@"报名" forState:UIControlStateNormal];
                    baoming.backgroundColor = themeColor;
                }
                else
                {
                    [baoming setTitle:[contentData objectForKey:@"EnrollStatusContent"] forState:UIControlStateNormal];
                    baoming.enabled = NO;
                    baoming.backgroundColor = [UIColor colorFromHexCode:@"b3b3b3"];
                }
                
                jobDescribe = [NSString stringWithFormat:@"%@",[contentData objectForKey:@"TaskDescription"]];
                [contentTableView reloadData];
            }
            else
            {
                [SVProgressHUD showErrorWithStatus:[resultDic objectForKey:@"message"]];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }
}

#pragma mark - tableview

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 11;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return [JobTableViewCell height];
    }
    else if (indexPath.row == 10)
    {
        return [JobDescribeTableViewCell heightWithData:jobDescribe];
    }
    else
    {
        return [JobDesctiptionTableViewCell height];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        static NSString * identifer = @"top";
        JobTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (!cell) {
            cell = [[JobTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
        }
        [cell loadData:contentData];
        return cell;
    }
    else if (indexPath.row == 10)
    {
        static NSString * identifer = @"top";
        JobDescribeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (!cell) {
            cell = [[JobDescribeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
        }
        [cell loadData:jobDescribe];
        return cell;
        
    }
    else
    {
        static NSString * identifer = @"top";
        JobDesctiptionTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (!cell) {
            cell = [[JobDesctiptionTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
        }
        if (indexPath.row == 1)
        {
            [cell loadData:@"课程名称" right:[contentData objectForKey:@"TaskName"]];
        }
        else if (indexPath.row == 2)
        {
            [cell loadData:@"服务类别" right:[contentData objectForKey:@"FuWuStyle"]];
        }
        else if (indexPath.row == 3)
        {
            [cell loadData:@"课程时间" right:[NSString stringWithFormat:@"%@-%@",[contentData objectForKey:@"TaskBeginTime"],[contentData objectForKey:@"TaskEndTime"]]];
        }
        else if (indexPath.row == 4)
        {
            NSString * str5 = @"";
            for (NSString * stt in [contentData objectForKey:@"TaskWeekday"]) {
                str5 = [str5 stringByAppendingString:stt];
                str5 = [str5 stringByAppendingString:@"  "];
            }
            [cell loadData:@"时间周期" right:str5];
        }
        else if (indexPath.row == 5)
        {
            [cell loadData:@"有效日期" right:[NSString stringWithFormat:@"%@-%@",[contentData objectForKey:@"TaskBeginDay"],[contentData objectForKey:@"TaskEndDay"]]];
        }
        else if (indexPath.row == 6)
        {
            [cell loadData:@"发布时间" right:[contentData objectForKey:@"PublishTime"]];
        }
        else if (indexPath.row == 7)
        {
            [cell loadData:@"价格" right:[contentData objectForKey:@"TaskPrice"]];
        }
        else if (indexPath.row == 8)
        {
            [cell loadData:@"位置" right:[NSString stringWithFormat:@"%@ %@",[contentData objectForKey:@"TaskProvinceID"],[contentData objectForKey:@"TaskCityID"]]];
        }
        else if (indexPath.row == 9)
        {
            [cell loadData:@"形式" right:[contentData objectForKey:@"OnOffLine"]];
        }
        return cell;
    }
}

-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    PersonDetailViewController * person = [[PersonDetailViewController alloc]init];
    person.uid = [contentData objectForKey:@"UserUID"];
    [self.navigationController pushViewController:person animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
